

import 'dart:isolate';

import 'package:development_assistant/config/dio_config.dart';
import 'package:development_assistant/model/auto_test.dart';
import 'package:development_assistant/model/test_api.dart';
import 'package:development_assistant/service/env_service.dart';
import 'package:development_assistant/service/test_service.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';

class TestController extends GetxController{

  @override
  void onInit() {
    // TODO: implement onInit
    getTestList();
  }

  var testName="".obs;
  var testEnv="测试环境".obs;
  var testThread=0.obs;
  var testCycles=0.obs;
  var testInterval=0.obs;


  var testApi=RxList<TestApi>();
  var testParams=[].obs;
  var testBody=[].obs;
  var testHeaders=[].obs;

  var apiName="".obs;
  var apiMethod="GET".obs;
  var apiUrl="".obs;
  var apiParams=[{
    "name":"",
    "param":""
  }].obs;
  var apiBody="".obs;
  var apiHeaders=[{
    "header":"",
    "param":""
  }].obs;

  var success=0.obs;
  var error=0.obs;
  var requestTime=0.obs;
  var averageTime=RxDouble(0.0);

  TestService testService=TestService();
  EnvService envService=EnvService();

  var pickIndex=0.obs;
  var testList=[].obs;
  var testApiList=[].obs;



  clear(){
    apiName.value="";
    apiMethod.value="GET";
    apiUrl.value="";
    apiParams.removeRange(0, apiParams.length-1);
    apiBody.value="";
    apiHeaders.removeRange(0,apiHeaders.length-1);
  }

  clearTest(){
    success.value=0;
    error.value=0;
    testParams.value=[];
    testBody.value=[];
    testHeaders.value=[];
    testApi.value=[];
  }

  Future test() async{
    var envResult=await envService.envInfo(testEnv.value);
    DioConfig dioConfig=DioConfig(envResult[0]['env_url']);
    var start=DateTime.now();
    for(var i=0;i<testThread.value;i++){
      for(var j=0;j<testCycles.value;j++){
        for(TestApi api in testApi){
          var index=0;
          Map<String,dynamic> paramsList={};
          Map<String,String> headersList={};
          for (var param in testParams[index]){
            if(param["name"]!=""){
              paramsList[param["name"]!]=param["param"];
            }
          }
          for (var header in testHeaders[index]){
            if(header["header"]!=""){
              headersList[header["header"]!]=header["param"]!;
            }
          }
          await Future.delayed(Duration(milliseconds: testInterval.value), ()async{
            try{
              switch (api.apiMethod){
                case "GET":
                  await dioConfig.get(api.apiUrl, paramsList,testBody[index].value, headersList);
                  break;
                case "POST":
                  await dioConfig.post(api.apiUrl, paramsList,testBody[index].value, headersList);
                  break;
                case "DELETE":
                  await dioConfig.delete(api.apiUrl, paramsList,testBody[index].value, headersList);
                  break;
                case "PUT":
                  await dioConfig.put(api.apiUrl, paramsList,testBody[index].value, headersList);
                  break;
              }
              success++;
            }catch(e){
              print(e);
              error++;
            }
          });
          index++;
        }
      }
    }
    var end=DateTime.now();
    requestTime.value=end.difference(start).inMilliseconds;
    averageTime.value=(requestTime.value/(testThread.value+testCycles.value));
    Get.snackbar("自动化测试".tr, "接口自动化测试完成".tr);
    Get.offNamed("/TestResult");

  }

  Future saveResult() async{
    String testDate = DateFormat('yyyy-MM-dd HH:mm').format(DateTime.now());
    AutoTest autoTest=
    AutoTest(null,testName.value, testEnv.value, testThread.value, testInterval.value,
        testCycles.value, success.value, error.value, requestTime.value, averageTime.value, testDate);
    await testService.addTest(autoTest, testApi);
    Get.snackbar("保存测试数据".tr, "成功保存测试数据".tr);
    clearTest();
  }

  Future delTest(int testID) async{
    pickIndex.value=0;
    await testService.delTest(testID);
    Get.snackbar("删除测试数据".tr, "成功删除测试数据".tr);
    Get.toNamed("/Home",arguments: {"selectIndex":2});
  }

  Future getTestList() async{
    var resMap=await testService.getTestList();
    testList=resMap[0];
    testApiList=resMap[1];
  }


}